package org.eclipsercp.hyperbola.views;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipsercp.hyperbola.Application;
import org.eclipsercp.hyperbola.common.UIConstants;
import org.eclipsercp.hyperbola.model.ContactEntry;
import org.eclipsercp.hyperbola.model.ContactGroup;
import org.eclipsercp.hyperbola.model.Presence;

@SuppressWarnings("rawtypes")
public class ContactApdaperFactory implements IAdapterFactory {

	public static final Map<Presence, String> ImageMap = new HashMap<Presence, String>();

	static {
		ImageMap.put(Presence.AWAY, UIConstants.Image.AWAY);
		ImageMap.put(Presence.DO_NOT_DISTURB, UIConstants.Image.DO_NOT_DISTURB);
		ImageMap.put(Presence.INVISIBLE, UIConstants.Image.OFFLINE);
		ImageMap.put(Presence.ONLINE, UIConstants.Image.ONLINE);
	}

	private IWorkbenchAdapter groupAdapter = new IWorkbenchAdapter() {

		@Override
		public Object getParent(Object o) {
			return ((ContactGroup) o).getParent();
		}

		@Override
		public String getLabel(Object o) {
			return ((ContactGroup) o).getName();
		}

		@Override
		public ImageDescriptor getImageDescriptor(Object object) {
			return AbstractUIPlugin.imageDescriptorFromPlugin(
					Application.PLUGIN_ID, UIConstants.Image.GROUP);
		}

		@Override
		public Object[] getChildren(Object o) {
			return ((ContactGroup) o).getEntries().toArray();
		}
	};
	private IWorkbenchAdapter entryAdapter = new IWorkbenchAdapter() {

		@Override
		public Object getParent(Object o) {
			return ((ContactEntry) o).getParent();
		}

		@Override
		public String getLabel(Object o) {
			return ((ContactEntry) o).getName();
		}

		@Override
		public ImageDescriptor getImageDescriptor(Object object) {
			ContactEntry entry = (ContactEntry) object;
			String key = ImageMap.get(entry.getPresence());

			return AbstractUIPlugin.imageDescriptorFromPlugin(
					Application.PLUGIN_ID, key);
		}

		@Override
		public Object[] getChildren(Object o) {
			return new Object[0];
		}
	};

	public Object getAdapter(Object adaptableObject, Class adapterType) {
		if (adapterType != IWorkbenchAdapter.class) {
			return null;
		} else {
			if (adaptableObject instanceof ContactGroup) {
				return groupAdapter;
			} else if (adaptableObject instanceof ContactEntry) {
				return entryAdapter;
			} else {
				return null;
			}
		}
	}

	public Class[] getAdapterList() {
		return new Class<?>[] { IWorkbenchAdapter.class };
	}

}
